import globalAxios, {type AxiosRequestConfig} from 'axios'
import {authService} from '@/service/AuthService'

export function initAxios(){
    globalAxios.defaults.baseURL = import.meta.env.VITE_API_URL

    let refreshTokenPromise: Promise<any> | null = null;
    function retryAfterRefreshToken(originalConfig: AxiosRequestConfig) {
        if (refreshTokenPromise === null) {
            refreshTokenPromise = new Promise(function (resolve, reject) {
                authService.refreshToken().then(resolve).catch(reject).finally(() => {
                    refreshTokenPromise = null;
                })
            });
        }
        return refreshTokenPromise.then(_ => globalAxios(originalConfig));
    }

    globalAxios.interceptors.request.use((config)=>{
        let accessToken = sessionStorage.getItem("access_token")
        if (accessToken){
            config.headers.setAuthorization("Bearer " + accessToken)
        }
        return config
    })

    globalAxios.interceptors.response.use((res)=>{
        return res;
    },
        (err)=>{
           if (err.response.status == 401) {
               return retryAfterRefreshToken(err.config)
           }
           return Promise.reject(err);
        }
    )
    /**/

}
